package bookstudytest.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @Auther: Lee
 * @Date: 2018/6/5 11:34
 * @Description:
 */
public class Handler {
    private int buffersize = 1024;
    private String localCharset = "UTF-8";

    public Handler() {
    }

    public Handler(int buffersize) {
        this(buffersize, null);
    }

    public Handler(String localCharset) {
        this(-1, localCharset);
    }

    public Handler(int buffersize, String localCharset) {
        this.buffersize = buffersize;
        this.localCharset = localCharset;
    }

    public void handlerAccept(SelectionKey selectionKey) throws IOException {
        SocketChannel accept = ((ServerSocketChannel) selectionKey.channel()).accept();
        accept.configureBlocking(false);
        accept.register(selectionKey.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(buffersize));
    }

    public void handleRead(SelectionKey selectionKey) throws IOException {
        //获得channel
        SocketChannel accept = (SocketChannel) selectionKey.channel();

        ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
        byteBuffer.clear();
        if (accept.read(byteBuffer) == -1) {
            accept.close();
        } else {
            //将buffer改为读状态
            byteBuffer.flip();
            //将buffer中的数据以localCharset编码，存入receive
            String receive = Charset.forName(localCharset).newDecoder().decode(byteBuffer).toString();
            System.out.println("receive 的字符串 ：" + receive);

            //返回数据给客户端
            String returnStr = "receive 的字符串 ：" + receive;
            byteBuffer = ByteBuffer.wrap(returnStr.getBytes(localCharset));
            accept.write(byteBuffer);
            accept.close();
        }

    }
}
